package com.csmz.mybookreadernew.UI.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.csmz.mybookreadernew.Bean.UserInfo;
import com.csmz.mybookreadernew.DBSQLite.DbMySQLite;
import com.csmz.mybookreadernew.R;
import com.csmz.mybookreadernew.Utils.Md5Utils;
import com.google.gson.Gson;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {
    private TextView tv_main_title;
    private TextView tv_back,tv_register,tv_find_psw;
    private Button btn_login,btn_login_qq;
    private String userName,psw,spPsw;
    private EditText et_user_name,et_psw;

    private static final String TAG = "LoginActivity";
    private static final String APP_ID = "1106830443";//官方获取的APPID
    private Tencent mTencent;
    private LoginActivity.BaseUiListener mIUiListener;
    private com.tencent.connect.UserInfo mUserInfo;     //qq用户信息
    private String mJsonSaveNameData;  //保存用户信息

    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //设置此界面为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();

        //传入参数APPID和全局Context上下文
        mTencent = Tencent.createInstance(APP_ID,LoginActivity.this.getApplicationContext());


    }

    /**
     * 获取界面控件
     */
    private void init() {
        tv_main_title= (TextView) findViewById(R.id.tv_main_title);
        tv_main_title.setText("登陆");
        tv_back= (TextView) findViewById(R.id.tv_back);
        tv_find_psw= (TextView) findViewById(R.id.tv_find_psw);
        tv_register= (TextView) findViewById(R.id.tv_register);
        btn_login= (Button) findViewById(R.id.btn_login);
        btn_login_qq = findViewById(R.id.btn_login_qq);
        et_user_name= (EditText) findViewById(R.id.et_user_name);
        et_psw= (EditText) findViewById(R.id.et_psw);


        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginActivity.this.finish();
            }
        });

        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });

        tv_find_psw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到找回密码界面
                startActivity(new Intent(LoginActivity.this,FindPswActivity.class));
            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userName=et_user_name.getText().toString().trim(); //获取用户名
                psw=et_psw.getText().toString().trim();//获取密码
                String md5Psw= Md5Utils.md5(psw);//加密
                spPsw=readPsw(userName);//读取密码
                if (TextUtils.isEmpty(userName)){
                    Toast.makeText(LoginActivity.this,"请输入用户名", Toast.LENGTH_SHORT).show();return;
                }else if (TextUtils.isEmpty(psw)){
                    Toast.makeText(LoginActivity.this,"请输入密码", Toast.LENGTH_SHORT).show();return;
                }else if (md5Psw.equals(spPsw)){
                    Toast.makeText(LoginActivity.this,"登陆成功", Toast.LENGTH_SHORT).show();
                    //保存登陆状态和登陆的用户名
                    saveloginStatus(true,userName);
                    //把成功的状态传递到MainActivity中
                    Intent data=new Intent();
                    data.putExtra("isLogin",true);
                    setResult(RESULT_OK,data);
                    finish();
                    startActivityForResult(new Intent(LoginActivity.this,MainActivity.class),1);
                    return;
                }else if ((!TextUtils.isEmpty(spPsw) && !md5Psw.equals(spPsw))){
                    Toast.makeText(LoginActivity.this,"输入的用户名和密码不一致", Toast.LENGTH_SHORT).show();return;
                }else{
                    Toast.makeText(LoginActivity.this,"此用户名不存在", Toast.LENGTH_SHORT).show();return;
                }


            }
        });

        btn_login_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
                 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
                 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类 */
                mIUiListener = new LoginActivity.BaseUiListener();
                //all表示获取所有权限
                mTencent.login(LoginActivity.this,"all", mIUiListener);

            }
        });
    }

    /**
     * 保存登陆状态的登陆用户名到SharedPreference
     *
     */
    private void saveloginStatus(boolean status,String userName) {
        SharedPreferences sp=getSharedPreferences("LoginInfo",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit(); //获取编辑器
        editor.putBoolean("isLogin",status);
        editor.putString("loginUserName",userName);//保存登陆时的用户名
        editor.commit();//提交修改
    }


    /**
     * 从SharedPreference中根据用户名读取密码
     */
    private String readPsw(String userName) {
        SharedPreferences sp=getSharedPreferences("LoginInfo",MODE_PRIVATE);
        //Log.d("csmz", "readPsw: "+sp.getString(userName,""));
        return sp.getString(userName,"");
    }

    /**
     * 获取到qq用户信息并保存
     * 用GSON解析单条Json数据
     */
    private void SaveMyQQUserMessage(){
        //JSONObject json = JSONObject.fromObject(mJsonSaveName);
        //创建GSON对象并解析：
        Gson gson = new Gson();
        UserInfo user=gson.fromJson(mJsonSaveNameData,UserInfo.class);
        userName = user.getNickname(); //获取用户名
        SPUtils.getInstance("QQ_User_Name").put("user_name",user.getNickname());
        //保存登陆状态和登陆的用户名
        saveloginStatus(true,userName);
        //把成功的状态传递到MainActivity中
        Intent data=new Intent();
        data.putExtra("isLogin",true);
        setResult(RESULT_OK,data);
        //把数据存储在数据库内
        DbMySQLite dbMySQLite = new DbMySQLite(this);
        if (dbMySQLite.findUserInfo(user.getNickname()) == null){
            dbMySQLite.addUserInfo(user.getNickname(),user.getYear(),user.getGender(),user.getCity());
        }
        Log.d(TAG, "findAllUserInfo: "+dbMySQLite.findAllUserInfo());
    }

    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener{

        @Override
        public void onComplete(Object response) {
            Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
            JSONObject obj = (JSONObject) response;
            try {
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new com.tencent.connect.UserInfo(getApplicationContext(),qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e(TAG,"登录成功"+response.toString());
                        mJsonSaveNameData =response.toString();
                        SaveMyQQUserMessage();
                        finish();
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    }

                    @Override
                    public void onError(UiError uiError) {
                        Log.e(TAG,"登录失败"+uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        Log.e(TAG,"登录取消");

                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();

        }

    }

    /**
     * 在调用Login的Activity或者Fragment中重写onActivityResult方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Constants.REQUEST_LOGIN){
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
